<!DOCTYPE HTML PUBLIC "-//ORA//DTD CD HTML 3.2//EN">
<HTML>
<HEAD>
<TITLE>[Chapter 2] 2.3 Hello Web! III: The Button Strikes!</TITLE>
<META NAME="author" CONTENT="Pat Niemeyer and Josh Peck">
<META NAME="date" CONTENT="Tue Jul 22 18:48:37 1997">
<META NAME="form" CONTENT="html">
<META NAME="metadata" CONTENT="dublincore.0.1">
<META NAME="objecttype" CONTENT="book part">
<META NAME="otheragent" CONTENT="gmat dbtohtml">
<META NAME="publisher" CONTENT="O'Reilly &amp; Associates, Inc.">
<META NAME="source" CONTENT="SGML">
<META NAME="subject" CONTENT="Java">
<META NAME="title" CONTENT="Exploring Java">
<META HTTP-EQUIV="Content-Script-Type" CONTENT="text/javascript">
</HEAD>
<body vlink="#551a8b" alink="#ff0000" text="#000000" bgcolor="#FFFFFF" link="#0000ee">

<DIV CLASS=htmlnav>
<H1><a href='index.htm'><IMG SRC="gifs/smbanner.gif"
     ALT="Exploring Java" border=0></a></H1>
<table width=515 border=0 cellpadding=0 cellspacing=0>
<tr>
<td width=172 align=left valign=top><A HREF="ch02_02.htm"><IMG SRC="gifs/txtpreva.gif" ALT="Previous" border=0></A></td>
<td width=171 align=center valign=top><B><FONT FACE="ARIEL,HELVETICA,HELV,SANSERIF" SIZE="-1">Chapter 2<br>A First Applet</FONT></B></TD>
<td width=172 align=right valign=top><A HREF="ch02_04.htm"><IMG SRC="gifs/txtnexta.gif" ALT="Next" border=0></A></td>
</tr>
</table>

&nbsp;
<hr align=left width=515>
</DIV>
<DIV CLASS=sect1>
<h2 CLASS=sect1><A CLASS="TITLE" NAME="EXJ-CH-SECT-3">2.3 Hello Web! III: The Button Strikes!</A></h2>

<P CLASS=para>
<A NAME="CH02.BUTTON"></A>Well, now that we have those concepts under control, we can move on to
some fun stuff. <tt CLASS=literal>HelloWeb3</tt> brings us a new graphical
interface component: the <tt CLASS=literal>Button</tt>. We add a
<tt CLASS=literal>Button</tt> component to our applet that changes the
color of our text each time the button is pressed. Our new example is
shown below.

<DIV CLASS=programlisting>
<P>
<PRE>
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class HelloWeb3 extends Applet 
    implements MouseMotionListener, ActionListener {
    int messageX = 125, messageY = 95;
    String theMessage;
    Button theButton;
    int colorIndex = 0;
    static Color[] someColors = { 
        Color.black, Color.red, Color.green, Color.blue, Color.magenta };
    
    public void init() {
        theMessage = getParameter("message");
        theButton = new Button("Change Color");
        add(theButton);
        addMouseMotionListener(this);
        theButton.addActionListener(this);
    }
    
    public void paint( Graphics gc ) {
        gc.drawString( theMessage, messageX, messageY );
    }
    public void mouseDragged( MouseEvent e ) {
        messageX = e.getX(); 
        messageY = e.getY();
        repaint();
    }
    public void mouseMoved( MouseEvent e ) { }
    public void actionPerformed( ActionEvent e ) {
        if ( e.getSource() == theButton ) {
            changeColor();
        }
    }
    synchronized private void changeColor() {
        if ( ++colorIndex == someColors.length )
            colorIndex = 0;
        setForeground( currentColor() );
        repaint();
    }
    synchronized private Color currentColor() {
        return someColors[ colorIndex ];
    }
}
</PRE>
</DIV>

<P CLASS=para>
Create <tt CLASS=literal>HelloWeb3</tt> just as the other applets and put
an <tt CLASS=literal>&lt;applet&gt;</tt> tag referencing it in an
HTML document. An <tt CLASS=literal>&lt;applet&gt;</tt>
tag just like the one for <tt CLASS=literal>HelloWeb2</tt> will do nicely.
Run the example, and you should see the display shown in <A HREF="ch02_03.htm#EXJ-CH-2-FIG-6">Figure 2.6</A>. Drag the text. Each time you press the
button the color should change. Call your friends!  They should be
duly impressed.

<DIV CLASS=figure>
<h4 CLASS=figure><A CLASS="TITLE" NAME="EXJ-CH-2-FIG-6">Figure 2.6: Hello Web! III</A></h4>


<p>
<img align=middle src="./figs/je0206.gif" alt="[Graphic: Figure 2-6]" width=503 height=273 border=0>

</DIV>

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="EXJ-CH-2-SECT-3.1">The New Operator</A></h3>

<P CLASS=para>
<A NAME="CH02.NEW"></A>So what have we added this time?  Well, for starters we have a new
variable:

<DIV CLASS=programlisting>
<P>
<PRE>
Button theButton; 
</PRE>
</DIV>

<P CLASS=para>
The <tt CLASS=literal>theButton</tt> variable is of type
<tt CLASS=literal>Button</tt> and is going to hold an instance of the
<tt CLASS=literal>java.awt.Button</tt> class. The
<tt CLASS=literal>Button</tt> class, as you might expect, represents a
graphical button, which should look like other buttons in
your windowing system.

<P CLASS=para>
Two additional lines in <tt CLASS=literal>init()</tt> actually create the
button and cause it to be displayed in our applet:

<DIV CLASS=programlisting>
<P>
<PRE>
theButton = new Button("Change Color"); 
add(theButton); 
</PRE>
</DIV>

<P CLASS=para>
The first line brings us to something new. The <tt CLASS=literal>new</tt>
keyword is used to create an instance of a class. Recall that the
variable we have declared is just an empty reference and doesn't yet
point to a real object--in this case, an instance of the
<tt CLASS=literal>Button</tt> class. This is a fundamental and
important concept. We have dealt with objects previously in our
examples. We have assigned them to variables, and we have called
methods in them. So far, however, these objects have always been
handed to us ready to go, and we have not had to explicitly create
them ourselves. In the case of our <tt CLASS=literal>paint()</tt> method,
we were given a <tt CLASS=literal>Graphics</tt> object with which to draw.
The system created this instance of the <tt CLASS=literal>Graphics</tt>
class for our area of the screen and passed it to us in the parameter
variable <tt CLASS=literal>gc</tt>. Our <tt CLASS=literal>theMessage</tt>
variable is of type <tt CLASS=literal>String</tt>, and we used it to hold a
<tt CLASS=literal>String</tt> that was returned by the
<tt CLASS=literal>getParameter()</tt> method. In each case, some other
method instantiated (created a new instance of) the class for us.

<P CLASS=para>
The closest we came to actually instantiating an object was when we
passed the name of the HTML
<tt CLASS=literal>&lt;applet&gt;</tt> parameter as an argument to the
<tt CLASS=literal>getParameter()</tt> method. In that case, we created
a <tt CLASS=literal>String</tt> object and passed it as the
argument, but we did it in a rather sneaky fashion. As I mentioned
previously, <tt CLASS=literal>String</tt> objects have special status in
the Java language. Because strings are used so frequently, the Java
compiler creates an instance of the <tt CLASS=literal>String</tt> class
for us whenever it comes across quoted text in our source code.
<tt CLASS=literal>String</tt> objects are, in all other respects, normal
objects. (See <A HREF="ch07_01.htm">Chapter 7, <i>Basic Utility Classes</i></A>.)

<P CLASS=para>
The <tt CLASS=literal>new</tt> operator provides the general mechanism for
instantiating objects. It's the feature of the Java language that
creates a new instance of a specified class. It arranges for Java to
allocate storage for the object and then calls the constructor method
of the objects' class to initialize it.

</DIV>

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="EXJ-CH-2-SECT-3.2">Constructors</A></h3>

<P CLASS=para>
A <I CLASS=emphasis>constructor</I> is a special method that is called
to set up a new instance of a class. When a new object is created,
Java allocates storage for it, sets variables to their default values,
and then calls the constructor method for the class to do
whatever application-level setup is required.

<P CLASS=para>
A constructor method looks like a method with the same name as its
class. For example, the constructor for the <tt CLASS=literal>Button</tt>
class is called <tt CLASS=literal>Button()</tt>. Constructors don't have
a return type; by definition they return an object of that class. But
like other methods, constructors can take arguments. Their sole
mission in life is to configure and initialize newly born class
instances, possibly using whatever information is passed to them in
parameters.

<P CLASS=para>
It's important to understand the difference between a
constructor and a method like our <tt CLASS=literal>init()</tt> method.
Constructors are special methods of a class that help set up and
initialize an instance of a class when it's first created. The
<tt CLASS=literal>init()</tt> method of the <tt CLASS=literal>Applet</tt>
class serves a very similar purpose; however, it's quite different.
Constructors are a feature of the Java language. Every class,
including <tt CLASS=literal>Applet</tt>, has constructors.
<tt CLASS=literal>init()</tt>, however, is just a method of the
<tt CLASS=literal>Applet</tt> class like any other. It's an
application-level phenomenon that happens to perform
initialization.

<P CLASS=para>
An object is created by using the <tt CLASS=literal>new</tt> operator with
the constructor for the class and any necessary arguments. The
resulting object instance is returned as a value. In our example, we
create a new instance of <tt CLASS=literal>Button</tt> and assign it to
our <tt CLASS=literal>theButton</tt> variable:

<DIV CLASS=programlisting>
<P>
<PRE>
theButton = new Button("Change Color"); 
</PRE>
</DIV>

<P CLASS=para>
This <tt CLASS=literal>Button</tt> constructor takes a
<tt CLASS=literal>String</tt> as an argument and, as it turns out, uses it
to set the label of the button on the screen. A class could also, of
course, provide methods that allow us to configure an object manually
after it's created or to change its configuration at a later time.
Many classes do both; the constructor simply takes its arguments
and passes them to the appropriate methods. The
<tt CLASS=literal>Button</tt> class, for example, has a public method,
<tt CLASS=literal>setLabel()</tt>, that allows us to set a
<tt CLASS=literal>Button</tt>'s label at any time. Constructors
with parameters are therefore a convenience that allows a sort of
short hand to set up a new object.

</DIV>

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="EXJ-CH-2-SECT-3.3">Method Overloading</A></h3>

<P CLASS=para>
I said this <tt CLASS=literal>Button</tt> constructor
because there could be more than one. A class can have multiple
constructors, each taking different parameters and possibly using them
to do different kinds of setup. When there are multiple constructors
for a class, Java chooses the correct one based on the types of
arguments that are passed to it. We call the
<tt CLASS=literal>Button</tt> constructor and pass it a
<tt CLASS=literal>String</tt> argument, so Java locates the constructor
method of the <tt CLASS=literal>Button</tt> class that takes a single
<tt CLASS=literal>String</tt> argument and uses it to set up the object.
This is called <I CLASS=emphasis>method overloading</I>. All methods
in Java, not just constructors, can be overloaded; this is one aspect
of the object-oriented programming principle of polymorphism.

<P CLASS=para>
A constructor method that takes no arguments is called the
<I CLASS=emphasis>default constructor</I>. As you'll see in
<A HREF="ch07_01.htm">Chapter 7, <i>Basic Utility Classes</i></A>, default constructors play a special role
in the initialization of inherited class members.

</DIV>

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="EXJ-CH-2-SECT-3.4">Garbage Collection</A></h3>

<P CLASS=para>
I've told you how to create a new object with the
<tt CLASS=literal>new</tt> operator, but I haven't said anything
about how to get rid of an object when you are done with it. If you
are a C programmer, you're probably wondering why not. The
reason is that you don't have to do anything to get rid of
objects when you are done with them.

<P CLASS=para>
The Java run-time system uses a <I CLASS=emphasis>garbage collection</I>
mechanism to deal with objects no longer in use. The garbage
collector sweeps up objects not referenced by any
variables and removes them from memory. Garbage collection is one of
the most important features of Java. It frees you from the
error-prone task of having to worry about details of memory
allocation and deallocation.

</DIV>

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="EXJ-CH-2-SECT-3.5">Components</A></h3>

<P CLASS=para>
I have used the terms <I CLASS=emphasis>component</I> and
<I CLASS=emphasis>container</I> somewhat loosely to describe graphical
elements of Java applications. However, you may recall from 
<A HREF="ch02_01.htm#EXJ-CH-2-FIG-3">Figure 2.3</A>
that these terms are the names of actual classes in the
<tt CLASS=literal>java.awt</tt> package.

<P CLASS=para>
<tt CLASS=literal>Component</tt> is a base class from which all of
Java's GUI components are derived. It
contains variables that represent the location, shape, general
appearance, and status of the object, as well as methods for basic
painting and event handling. The familiar
<tt CLASS=literal>paint()</tt> method we have been using in
our example is actually inherited from the
<tt CLASS=literal>Component</tt> class. <tt CLASS=literal>Applet</tt> is, of
course, a kind of <tt CLASS=literal>Component</tt> and inherits all of its
public members, just as other (perhaps simpler) types of
GUI components do.

<P CLASS=para>
The <tt CLASS=literal>Button</tt> class is also derived from
<tt CLASS=literal>Component</tt> and therefore shares this
functionality. This means that the developer of the
<tt CLASS=literal>Button</tt> class had methods like
<tt CLASS=literal>paint()</tt>
available with which to implement the behavior of the
<tt CLASS=literal>Button</tt> object, just as we did when creating our
applet.
What's exciting is that we are perfectly free to further
subclass components like <tt CLASS=literal>Button</tt> and override their
behavior to create our own special types of user-interface components.

<P CLASS=para>
Both <tt CLASS=literal>Button</tt> and <tt CLASS=literal>Applet</tt> are, in
this respect, equivalent types of things. However, the
<tt CLASS=literal>Applet</tt> class is further derived from a class called
<tt CLASS=literal>Container</tt>, which gives it the added ability to hold
other components and manage them.

</DIV>

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="EXJ-CH-2-SECT-3.6">Containers</A></h3>

<P CLASS=para>
A <tt CLASS=literal>Button</tt> object is a simple GUI
component. It makes sense only in the context of some larger
application. The <tt CLASS=literal>Container</tt> class is an extended
type of <tt CLASS=literal>Component</tt> that maintains a list of child
components and helps to group them. The <tt CLASS=literal>Container</tt>
causes its children to be displayed and arranges them on the screen
according to a particular scheme. A <tt CLASS=literal>Container</tt> may
also receive events related to its child components. As I mentioned
earlier, if a component doesn't respond to a particular type of
event by overriding the appropriate event-handling method and handling
the event, the event is passed to the parent
<tt CLASS=literal>Container</tt> of the component. This is the default
behavior for the standard Java AWT components,
which gives us a great deal of flexibility in managing interface
components. We could, for example, create a smart button by
subclassing the <tt CLASS=literal>Button</tt> class and overriding certain
methods to deal with the action of being pressed. Alternatively, we
could simply have the <tt CLASS=literal>Button</tt>'s container note
which <tt CLASS=literal>Button</tt> is pressed and handle the event
appropriately. In the interest of keeping our examples contained in a
single class, I am using the gestalt view and letting our
<tt CLASS=literal>Button</tt>'s container,
<tt CLASS=literal>HelloWeb3</tt>, deal with its events.

<P CLASS=para>
Remember that a <tt CLASS=literal>Container</tt> is a
<tt CLASS=literal>Component</tt> too and, as such, can be placed alongside
other <tt CLASS=literal>Component</tt> objects in other
<tt CLASS=literal>Containers</tt>, in a hierarchical fashion, as shown in
<A HREF="ch02_03.htm#EXJ-CH-2-FIG-7">Figure 2.7</A>. Our <tt CLASS=literal>HelloWeb3</tt>
applet is a kind of <tt CLASS=literal>Container</tt> and can therefore
hold and manage other Java AWT components and
containers like buttons, sliders, text fields, and panels.

<DIV CLASS=figure>
<h4 CLASS=figure><A CLASS="TITLE" NAME="EXJ-CH-2-FIG-7">Figure 2.7: A hypothetical layout of Java containers and components</A></h4>


<p>
<img align=middle src="./figs/je0207.gif" alt="[Graphic: Figure 2-7]" width=503 height=223 border=0>

</DIV>

<P CLASS=para>
In <A HREF="ch02_03.htm#EXJ-CH-2-FIG-7">Figure 2.7</A>, the italicized items are
components, and the bold items are containers. The keypad is
implemented as a container object that manages a number of keys. The
keypad itself is contained in the <tt CLASS=literal>GizmoTool</tt>
container object.

</DIV>

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="EXJ-CH-2-SECT-3.7">Layout</A></h3>

<P CLASS=para>
After creating the <tt CLASS=literal>Button</tt> object, we'd like to
stick it in our applet. To do so, we invoke the
<tt CLASS=literal>add()</tt> method of <tt CLASS=literal>Applet</tt>, passing
the <tt CLASS=literal>Button</tt> object as a parameter:

<DIV CLASS=programlisting>
<P>
<PRE>
add(theButton); 
</PRE>
</DIV>

<P CLASS=para>
<tt CLASS=literal>add()</tt> is a method inherited by our
<tt CLASS=literal>Applet</tt> from the <tt CLASS=literal>Container</tt> class.
It appends our <tt CLASS=literal>Button</tt> to the list of components
<tt CLASS=literal>HelloWeb3</tt> manages. Thereafter,
<tt CLASS=literal>HelloWeb3</tt> is responsible for the
<tt CLASS=literal>Button</tt>: the applet causes the button to be
displayed, it determines where in our part of the screen the button
should be placed, and it receives events when the button is pushed.

<P CLASS=para>
 
Java uses an object called a <tt CLASS=literal>LayoutManager</tt> to determine
the precise location in <tt CLASS=literal>HelloWeb3</tt>'s screen
area the <tt CLASS=literal>Button</tt> is displayed. A
<tt CLASS=literal>LayoutManager</tt> object embodies a particular scheme
for arranging components on the screen and adjusting their sizes.
You'll learn more about layout managers in <A HREF="ch12_01.htm">Chapter 12, <i>Layout Managers</i></A>. There are several standard layout managers to
choose from, and we can, of course, create new ones. In our case, we
have not specified a layout manager, so we get the default one, which
means our button appears centered at the top of the applet.

</DIV>

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="EXJ-CH-2-SECT-3.8">Subclassing and Subtypes</A></h3>

<P CLASS=para>
If you look up the <tt CLASS=literal>add()</tt> method of the
<tt CLASS=literal>Container</tt> class, you'll see that it takes a
<tt CLASS=literal>Component</tt> object as an argument. But in our example
we've given it a <tt CLASS=literal>Button</tt> object. What's
going on?

<P CLASS=para>
Well, if you check the inheritance diagram in <A HREF="ch02_01.htm#EXJ-CH-2-FIG-3">Figure 2.3</A> again, you'll see that
<tt CLASS=literal>Button</tt> is a subclass of the
<tt CLASS=literal>Component</tt> class. Because a subclass is a kind of
its superclass and has, at minimum, the same public methods and
variables, we can use an instance of a subclass anywhere we use
an instance of its superclass. This is a very important concept, and
it's a second aspect of the object-oriented principle of
polymorphism. <tt CLASS=literal>Button</tt> is a kind of
<tt CLASS=literal>Component</tt>, and any method that expects a
<tt CLASS=literal>Component</tt> as an argument will accept a
<tt CLASS=literal>Button</tt>.

</DIV>

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="EXJ-CH-2-SECT-3.9">More Events and Interfaces</A></h3>

<P CLASS=para>
Now that we have a <tt CLASS=literal>Button</tt>, 
we need some way to communicate with it:
that is, to get the events it generates. We could just listen for
mouse clicks, figure out whether they were close enough to the button,
and act accordingly. But that would take a lot of work, and would give
up the advantages of using a pre-built component. Buttons generate a
special kind of event called an
<tt CLASS=literal>ActionEvent</tt> 
when someone clicks on
them. To receive these events, we have added another method to our class: 

<DIV CLASS=programlisting>
<P>
<PRE>
public void actionPerformed( ActionEvent e ) {
    if ( e.getSource() == theButton ) {
        changeColor();
    }
}
</PRE>
</DIV>

<P CLASS=para>
If you understood the previous applet, you shouldn't be surprised to
see that <tt CLASS=literal>HelloWeb3</tt> now declares that it
implements the <tt CLASS=literal>ActionListener</tt> interface,
in addition to <tt CLASS=literal>MouseMotionListener</tt>.
<tt CLASS=literal>ActionListener</tt> requires us to implement an
<tt CLASS=literal>actionPerformed()</tt> method, which is called
whenever an <tt CLASS=literal>ActionEvent</tt> occurs. You also
shouldn't be surprised to see that we added a line to
<tt CLASS=literal>init()</tt>, registering the applet as a
listener for the button's action events: this is the call to
<tt CLASS=literal>theButton.addActionListener(this)</tt>.

<P CLASS=para>
The <tt CLASS=literal>actionPerformed()</tt> method takes care of
any action events that arise. First, it checks to make sure that the
event's source (the component generating the event) is what we think
it should be: <tt CLASS=literal>theButton</tt>, the only button
we've put in the applet. This may seem superfluous; after all, what
else could possibly generate an action event? In this applet,
nothing. But it's a good idea to check, because another applet may
have several buttons, and you may need to figure out which one is
meant. Or you may add a second button to this applet later, and you
don't want the applet to break something. To make this check, we call
the <tt CLASS=literal>getSource()</tt> method of the
<tt CLASS=literal>ActionEvent</tt> object,
<tt CLASS=literal>e</tt>. Then we use the "==" operator to make
sure that the event source matches <tt CLASS=literal>theButton</tt>.  Remember that in Java,
== is a test for identity, not equality; it is true if the event
source and <tt CLASS=literal>theButton</tt> are the same
object. The distinction between equality and identity is important. We
would consider two <tt CLASS=literal>String</tt> objects to be
equal if they have the same characters in the same sequence. However,
they might not be the same object. 
In <A HREF="ch05_01.htm">Chapter 5, <i>Objects in Java</i></A>, we'll look at the
<tt CLASS=literal>equals()</tt> method, which tests for
equivalence. Once we establish that the event
<tt CLASS=literal>e</tt> comes from the right button, we call our
<tt CLASS=literal>changeColor()</tt> method, and we're done.

<P CLASS=para>
You may be wondering why we don't have to change
<tt CLASS=literal>mouseDragged()</tt> now that we have a
<tt CLASS=literal>Button</tt> in our applet. The rationale is that the
coordinates of the event are all that matter for this method. We are
not particularly concerned if the event happens to fall within an area
of the screen occupied by another component. This means that you
can drag the text right through the <tt CLASS=literal>Button</tt> and
even lose it behind the <tt CLASS=literal>Button</tt> if you aren't
careful: try it and see!

</DIV>

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="EXJ-CH-2-SECT-3.10">Color Commentary</A></h3>

<P CLASS=para>
<A NAME="CH02.COLOR"></A>To support <tt CLASS=literal>HelloWeb3</tt>'s colorful side we have
added a couple of new variables and two helpful methods. We create and
initialize an array of <tt CLASS=literal>Color</tt> objects representing
the colors through which we cycle when the button is pressed. We also
declare an integer variable that serves as an index to this array,
specifying the current color:

<DIV CLASS=programlisting>
<P>
<PRE>
Color[] someColors = { 
    Color.black, Color.red, Color.green, Color.blue, Color.magenta }; 
int colorIndex; 
</PRE>
</DIV>

<P CLASS=para>
A number of things are going on here. First let's look at the
<tt CLASS=literal>Color</tt> objects we are putting into the array.
Instances of the <tt CLASS=literal>java.awt.Color</tt> class represent
colors and are used by all classes in the <tt CLASS=literal>java.awt</tt>
package that deal with color graphics. Notice that we are referencing
variables such as <tt CLASS=literal>Color.black</tt> and
<tt CLASS=literal>Color.red</tt>. These look like normal references to an
object's instance variables; however <tt CLASS=literal>Color</tt> is
not an object, it's a class. What is the meaning of this?

</DIV>

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="EXJ-CH-2-SECT-3.11">Static Members</A></h3>

<P CLASS=para>
If you recall our discussion of classes and instances, I hinted then
that a class can contain methods and variables that are shared among
all instances of the class. These shared members are called
<I CLASS=emphasis>static variables</I> and <I CLASS=emphasis>static
methods</I>. The most common use of static variables in a class
is to hold predefined constants or unchanging objects all of the
instances can use.

<P CLASS=para>
There are two advantages to this approach. The more obvious advantage
is that static members take up space only in the class; the members
are not replicated in each instance. The second advantage is that
static members can be accessed even if no instances of the class
exist. A hypothetical <tt CLASS=literal>Component</tt> class might have a
static variable called <tt CLASS=literal>maximumWidth</tt>. Some other
class that has to deal with this component, such as a layout manager,
might want to know the maximum width of such a component, even if
there aren't any around at the moment. Since
<tt CLASS=literal>maximumWidth</tt> is a static variable, the layout
manager can get this information.

<P CLASS=para>
An instance of the <tt CLASS=literal>Color</tt> class represents a color.
For convenience, the <tt CLASS=literal>Color</tt> class contains some
static, predefined color objects with friendly names like
<tt CLASS=literal>green</tt>, <tt CLASS=literal>red</tt>, and (my favorite)
<tt CLASS=literal>magenta</tt>. <tt CLASS=literal>Color.green</tt> is thus a
predefined <tt CLASS=literal>Color</tt> object that is set to a green
color. In this case, these static members of <tt CLASS=literal>Color</tt>
are not changeable, so they are effectively constants and can be
optimized as such by the compiler. Constant static members make up
for the lack of a <tt CLASS=literal>#define</tt> construct in Java.
However, static variables don't, in general, have to be constant.
I'll say more about static class members in <A HREF="ch05_01.htm">Chapter 5, <i>Objects in Java</i></A>.
The alternative to using these predefined colors is to create a color
manually by specifying its red, green, blue (RGB) components using a
<tt CLASS=literal>Color</tt> class constructor.

</DIV>

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="EXJ-CH-2-SECT-3.12">Arrays</A></h3>

<P CLASS=para>
<A NAME="CH02.ARRAYS"></A>Next, we turn our attention to the array. We have declared a variable
called <tt CLASS=literal>someColors</tt>, which is an array of
<tt CLASS=literal>Color</tt> objects. Arrays are syntactically supported
by the Java language; however, they are true, first-class objects.
This means that an array is, itself, a type of object that knows how
to hold an indexed list of some other type of object. An array is
indexed by integers; when you index an array, the resulting value is
the object in the corresponding slot in the array. Our code uses the
<tt CLASS=literal>colorIndex</tt> variable to index
<tt CLASS=literal>someColors</tt>. It's also possible to have an array of
simple primitive types, rather than objects.

<P CLASS=para>
When we declare an array, we can initialize it by using the familiar
C-like curly brace construct. Specifying a comma-separated list of
elements inside of curly braces is a convenience that instructs the
compiler to create an instance of the array with those elements and
assign it to our variable. Alternatively, we could have just declared
our <tt CLASS=literal>someColors</tt> variable and, later, allocated an
array object for it and assigned individual elements to that
array's slots. See <A HREF="ch04_01.htm">Chapter 4, <i>The Java Language</i></A> for a complete
discussion of arrays.

</DIV>

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="EXJ-CH-2-SECT-3.13">Our Color Methods</A></h3>

<P CLASS=para>
So, we now have an array of <tt CLASS=literal>Color</tt> objects and a
variable with which to index them. What do we do with them?  Well, we
have declared two private methods that do the actual work for us. The
<tt CLASS=literal>private</tt> modifier on these methods specifies that
they can be called only by other methods in the same instance of the
class. They are not visible outside of the object. We declare members
to be <tt CLASS=literal>private</tt> to hide the detailed inner workings
of a class from the outside world. This is called
<I CLASS=emphasis>encapsulation</I> and is another tenet of
object-oriented design, as well as good programming practice. Private
methods are also often created as helper functions for use solely
within the class implementation.

<P CLASS=para>
The first method, <tt CLASS=literal>currentColor()</tt>, is simply a
convenience routine that returns the <tt CLASS=literal>Color</tt> object
representing the current text color. It returns the
<tt CLASS=literal>Color</tt> object in the <tt CLASS=literal>someColors</tt>
array at the index specified by our <tt CLASS=literal>colorIndex</tt>
variable:

<DIV CLASS=programlisting>
<P>
<PRE>
synchronized private Color currentColor() { 
    return someColors[ colorIndex ]; 
} 
</PRE>
</DIV>

<P CLASS=para>
We could just as readily have used the expression
<tt CLASS=literal>someColors[colorIndex]</tt> everywhere we use
<tt CLASS=literal>currentColor()</tt>; however, creating methods to wrap
common tasks is another way of shielding ourselves from the details of
our class. In an alternative implementation, we might have shuffled
off details of all color-related code into a separate class.
We could have created a class that takes an array of colors in its
constructor and then provided two methods: one to ask for the current
color and one to cycle to the next color (just some food for
thought).

<P CLASS=para>
The second method, <tt CLASS=literal>changeColor()</tt>, is responsible
for incrementing the <tt CLASS=literal>colorIndex</tt> variable to point
to the next <tt CLASS=literal>Color</tt> in the array.
<tt CLASS=literal>changeColor()</tt> is called from our
<tt CLASS=literal>action()</tt> method whenever the button is pressed.

<DIV CLASS=programlisting>
<P>
<PRE>
synchronized private void changeColor() { 
    if ( ++colorIndex == someColors.length ) 
        colorIndex = 0; 
    setForeground( currentColor() ); 
    repaint(); 
} 
</PRE>
</DIV>

<P CLASS=para>
We increment <tt CLASS=literal>colorIndex</tt> and compare it to the
length of the <tt CLASS=literal>someColors</tt> array. All array objects
have a variable called <tt CLASS=literal>length</tt> that specifies the
number of elements in the array. If we have reached the end of the
array, we reset our index to zero and start over. After changing the
currently selected color, we do two things. First, we call the
applet's <tt CLASS=literal>setForeground()</tt> method, which
changes the color used to draw 
text in the applet and the color of the button's label. Then we call
<tt CLASS=literal>repaint()</tt> to cause the applet to be redrawn with
the new color for the draggable message.

<P CLASS=para>
So, what is the <tt CLASS=literal>synchronized</tt> keyword that appears
in front of our <tt CLASS=literal>currentColor()</tt> and
<tt CLASS=literal>changeColor()</tt> methods?  Synchronization has to do
with threads, which we'll examine in the next section. For now,
all you need know is that the <tt CLASS=literal>synchronized</tt>
keyword indicates these two methods can never be running at the
same time. They must always run one after the other.

<P CLASS=para>
The reason is that in <tt CLASS=literal>changeColor()</tt> we increment
<tt CLASS=literal>colorIndex</tt> before testing its value. That means
that for some brief period of time while Java is running through
our code, <tt CLASS=literal>colorIndex</tt> can have a value that is past
the end of our array. If our <tt CLASS=literal>currentColor()</tt> method
happened to run at that same moment, we would see a run-time
"array out of bounds" error. There are, of course, ways
in which we could fudge around the problem in this case, but this
simple example is representative of more general synchronization
issues we need to address. In the next section, you'll see
that Java makes dealing with these problems easy through
language-level synchronization support.

</DIV>

</DIV>


<DIV CLASS=htmlnav>

<P>
<HR align=left width=515>
<table width=515 border=0 cellpadding=0 cellspacing=0>
<tr>
<td width=172 align=left valign=top><A HREF="ch02_02.htm"><IMG SRC="gifs/txtpreva.gif" ALT="Previous" border=0></A></td>
<td width=171 align=center valign=top><a href="index.htm"><img src='gifs/txthome.gif' border=0 alt='Home'></a></td>
<td width=172 align=right valign=top><A HREF="ch02_04.htm"><IMG SRC="gifs/txtnexta.gif" ALT="Next" border=0></A></td>
</tr>
<tr>
<td width=172 align=left valign=top>Hello Web! II: The Sequel</td>
<td width=171 align=center valign=top><a href="index/idx_0.htm"><img src='gifs/index.gif' alt='Book Index' border=0></a></td>
<td width=172 align=right valign=top>Hello Web! IV: Netscape's Revenge</td>
</tr>
</table>
<hr align=left width=515>

<IMG SRC="gifs/smnavbar.gif" USEMAP="#map" BORDER=0> 
<MAP NAME="map"> 
<AREA SHAPE=RECT COORDS="0,0,108,15" HREF="../javanut/index.htm"
alt="Java in a Nutshell"> 
<AREA SHAPE=RECT COORDS="109,0,200,15" HREF="../langref/index.htm" 
alt="Java Language Reference"> 
<AREA SHAPE=RECT COORDS="203,0,290,15" HREF="../awt/index.htm" 
alt="Java AWT"> 
<AREA SHAPE=RECT COORDS="291,0,419,15" HREF="../fclass/index.htm" 
alt="Java Fundamental Classes"> 
<AREA SHAPE=RECT COORDS="421,0,514,15" HREF="../exp/index.htm" 
alt="Exploring Java"> 
</MAP>
</DIV>

</BODY>
</HTML>
